# coding: utf-8
import re
import paramiko

# 认证信息（建议使用配置文件或环境变量）
username = "opsadmin"
password = "OPS#2528sjzx"
ip = "10.255.253.234"
port = 22


def get_ssh_connection(ip, port, username, password):
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, username, password, timeout=2000, allow_agent=False, look_for_keys=False)
    return ssh


def execute_command(ssh, command):
    stdin, stdout, stderr = ssh.exec_command(command)
    return stdout.read().decode()


def get_system():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display version | no-more")
    # 精准匹配主设备运行时间（包含设备型号校验）
    pattern = r'^HUAWEI\s*NetEngine\s*8000\s*M8\s*uptime\s*is\s*(\d+\sdays,\s\d+\shours,\s\d+\sminutes)\r*$'
    uptime_match = re.search(pattern, output, re.MULTILINE | re.VERBOSE)
    if uptime_match:
        uptime = uptime_match.group(1)
        print(f'[XJ]系统-运行时长#{uptime}#正常#获取系统信息#无')
    else:
        print('[XJ]系统-运行时长#None#异常#未获取系统信息#请检查')
    ssh.close()

def get_device():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display device | no-more")
    # 正则表达式模式（智能匹配列偏移）
    pattern = re.compile(
        r'^(\d+)\s+'  # Slot号
        r'(\S+)\s+'  # Type列
        r'\S+\s+'  # Online列（跳过）
        r'\S+\s+'  # Register列（跳过）
        r'(\S+)\s+'  # Status列
        r'.*$',
        re.MULTILINE
    )
    # 处理数据
    status_report = []
    for match in pattern.finditer(output):
        slot, dev_type, status = match.groups()
        status_report.append({
            'slot': slot,
            'type': dev_type,
            'status': status
        })
    for item in status_report:
        key= item['slot']+item['type']
        value = item['status']
        print(f"[XJ]系统-板卡信息{key}#{value}#正常#获取板卡信息#无")
    ssh.close()

def get_fan():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display fan | no-more")
    fan_match = re.search(r'Status\s*:\s*(\w+)',output)
    if fan_match:
        fan_status = fan_match.group(1)
        if fan_status == 'AUTO':
            print(f"[XJ]系统-风扇信息#{fan_status}#正常#获取板卡信息#无")
        else:
            print(f"[XJ]系统-风扇信息#{fan_status}#异常#获取板卡信息#无")
    ssh.close()

def get_power():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display power | no-more")
    pattern = re.compile(
        r'^(\d+)\s+'  # No
        r'\S+\s+'  # Present列（跳过）
        r'\S+\s+'  # Mode列（跳过）
        r'(\S+)\s+'  # Status列
        r'.*$',
        re.MULTILINE
    )
    # 处理数据
    status_report = []
    for match in pattern.finditer(output):
        no, status = match.groups()
        status_report.append({
            'no': no,
            'status': status
        })
    for item in status_report:
        key = "电源{}".format(item['no'])
        value = item['status']
        print(f"[XJ]系统-{key}状态#{value}#正常#获取板卡信息#无")
    ssh.close()

def get_cpu():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display cpu-usage | no-more")
    cpu_match = re.search(r'System\s*cpu\s*use\s*rate\s*is\s*:\s*(\d+)%', output)
    if cpu_match:
        cpu_usage = int(cpu_match.group(1))
        status = "正常" if cpu_usage < 70 else "异常"  # 路由器CPU阈值调整为70%
        print(
            f"[XJ]性能-CPU使用率#{cpu_usage}%#{status}#{'小于' if cpu_usage < 70 else '大于等于'}70%#{'无' if cpu_usage < 70 else '建议检查进程'}")
    ssh.close()

def get_mem():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display memory-usage | no-more")
    mem_match = re.search(r'Memory\s*Using\s*Percentage\s*Is:\s*(\d+)%', output)
    if mem_match:
        mem_usage = int(mem_match.group(1))
        status = "正常" if mem_usage < 75 else "异常"  # 路由器内存阈值调整为75%
        print(
            f"[XJ]性能-内存使用率#{mem_usage}%#{status}#{'小于' if mem_usage < 75 else '大于等于'}75%#{'无' if mem_usage < 75 else '建议检查内存'}")
    ssh.close()

def get_interface():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display interface brief | no-more")
    for line in output.splitlines():
        if re.match(r'^(GigabitEthernet|Eth-Trunk|Ethernet|Vlanif)', line):
            interface = line[:28].strip()
            status = line[28:34].strip()
            print(f"[XJ]接口-{interface}#{status}#正常#接口状态up#无")
    ssh.close()

def get_temperature():
    ssh = get_ssh_connection(ip, port, username, password)
    output = execute_command(ssh, "display temperature | no-more")
    pattern = re.compile(
        r'^(\w+)\s+'  # PCB
        r'\S+\s+'  # I2C列（跳过）
        r'\S+\s+'  # Addr列（跳过）
        r'\S+\s+'  # Chl列
        r'\S+\s+'  # Status列
        r'\S+\s+'  # Minor列
        r'\S+\s+'  # Major列
        r'\S+\s+'  # Fatal列
        r'\S+\s+'  # FanTMin列
        r'\S+\s+'  # FanTMax列
        r'(\S+)\s+',  # Temp列
        re.MULTILINE
    )
    # 处理数据
    status_report = []
    for match in pattern.finditer(output):
        pcb, temp = match.groups()
        status_report.append({
            'pcb': pcb,
            'temp': temp
        })
    for item in status_report:
        key = item['pcb']
        value = item['temp']
        print(type(value))
        if key != 'PCB':
            if int(value) <= 105:
                print(f"[XJ]温度-{key}温度#{value}°C#正常#当前温度小于等于105#无")
            else:
                print(f"[XJ]温度-{key}温度#{value}°C#异常#当前温度大105#请检查设备")
    ssh.close()




if __name__ == '__main__':
    try:
        get_system()
        get_device()
        get_fan()
        get_power()
        get_cpu()
        get_mem()
        get_interface()
        get_temperature()
    except:
        print(f"[XJ]系统信息-连接状态#未连接#异常#SSH连接失败#无")